package main

import (
	"net"
	"os"
	"fmt"
	"log"
	"git.oschina.net/solate/test/other/tcp/protocol"
	"time"
)

func main() {

	//建立tcp连接
	netListen, err := net.Listen("tcp", "localhost:9998")
	checkErr(err)
	defer netListen.Close()


	log.Println("waiting for clients")
	for   {
		conn, err := netListen.Accept()
		if err != nil {
			log.Println("conn err:", err.Error())
			continue
		}


		//设置超时时间
		conn.SetReadDeadline(time.Now().Add(10 * time.Second))
		log.Println("tcp connect success:", conn.RemoteAddr().String())
		go handleConn(conn)

	}

}

//处理链接
func handleConn(conn net.Conn)  {
	defer conn.Close()

	// 缓冲区，存储被截断的数据
	tmpBuffer := make([]byte, 0)

	//接收解包
	readerChannel := make(chan []byte, 16)
	go reader(readerChannel)


	//这里改成2048, 因为如果是1024正好读不完一个消息，所以这个是后面处理如果是半包的问题该怎么解决
	//这里只展示了沾包的时候处理方式：用协议
	buffer := make([]byte, 2048)

	for {
		n, err := conn.Read(buffer)
		if err != nil {
			log.Println(conn.RemoteAddr().String()," conn read err:", err.Error())
			return
		}

		log.Println(conn.RemoteAddr().String(), "receive data string:\n", string(buffer[:n]))

		tmpBuffer = protocol.Depack(append(tmpBuffer, buffer[:n]...))
	}

}

func reader(readerChannel chan []byte)  {
	for {
		select {
		case data:= <-readerChannel:
			log.Println(string(data))
		}
	}
}



func checkErr(err error)  {
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error:%s", err.Error())
		os.Exit(1)
	}
}